<?php
/**
 * @author guoxiaoyong
 */
namespace bc\model\product\detail;

use bc\ar\MActiveRecord;
use bc\model\product\DistributionModel;
use bc\util\Math;

class BounsModel extends MActiveRecord
{
	
	public $autoId = 'bouns_id';
	
	public static function tableName()
	{
		return '{{%order_detai_bouns}}';
	}
	
	
	
	/**
	 * 插入多级分利  使用事务
	 * @param array $muliData
	 * @param int $productId
	 * @return boolean
	 */
	public function createBouns($muliData, $productId, $detailId)
	{
		$distributionModel = new DistributionModel();
		$distribution = $distributionModel->getRow(['product_id' => $productId, 'is_del' => 0]);
		
		if($distribution)
		{
			$current_time = date('Y-m-d H:i:s');
			$transaction = $this->getDb()->beginTransaction();
			try
			{
				foreach ($muliData as $level=>$item)
				{
					$bouns = Math::ConverToCeil($distribution['distribution_price'] * $distribution['level_' . $level], 1);
					$sql = 'INSERT ' . self::getTableSchema ()->name . "(detail_id, product_id, user_id, level, bouns, is_del, create_time, update_time) VALUES ( {$detailId}, {$productId}, {$item['user_id']}, {$level}, '{$bouns}', 0, '{$current_time}', '{$current_time}')";
					$this->getDb()->createCommand($sql)->execute();
				}
			
				$transaction->commit();
				return true;
			}
			catch (\Exception $e)
			{
				$transaction->rollBack();
				throw $e;
			}
		}
		else 
		{
			return false;
		}
		
	}
}

